
from dvadmin.knowledge.models import Documents
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.viewset import CustomModelViewSet
from rest_framework.decorators import action
from rest_framework import serializers
from dvadmin.utils.json_response import SuccessResponse, ErrorResponse, DetailResponse


class documentsSerializer(CustomModelSerializer):
    """
    区块-序列化器
    """
    class Meta:
        model = Documents
        fields = "__all__"
        read_only_fields = ["id"]

class treeDocumentSerializer(CustomModelSerializer):
    """
    前端菜单路由的简单序列化器
    """
    value = serializers.IntegerField(source="id")
    key = serializers.IntegerField(source="id")

    label = serializers.CharField(source="name")
    class Meta:
        model = Documents
        fields = '__all__'
        fields = ('label', 'value','parent',"key")


class edittreeDocumentSerializer(CustomModelSerializer):
    """
    前端菜单路由的简单序列化器
    """
    value = serializers.IntegerField(source="id")
    key = serializers.IntegerField(source="id")

    label = serializers.CharField(source="edittree")
    class Meta:
        model = Documents
        fields = '__all__'
        fields = ('label', 'value','parent',"key")


class BasisViewSet(CustomModelViewSet):
    """
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = Documents.objects.all()
    serializer_class = documentsSerializer
    permission_classes = []
    @action(methods=['GET'], detail=False)
    def edittree(self, request):
        book = request.query_params['bookid']
        obj = Documents.objects.filter(book_id = int(book))

        """路有树"""
        serializer = edittreeDocumentSerializer(obj, many=True, request=request)
        data = serializer.data
        return SuccessResponse(data=data, total=len(data), msg="获取成功")
    @action(methods=['GET'], detail=False)
    def tree(self, request):
        book = request.query_params['bookid']
        obj = Documents.objects.filter(book_id = int(book))

        """路有树"""
        serializer = treeDocumentSerializer(obj, many=True, request=request)
        data = serializer.data
        return SuccessResponse(data=data, total=len(data), msg="获取成功")
    def retrieve(self, request, *args, **kwargs):
        self.extra_filter_backends = []
        instance = self.get_object()
        if (instance.book.privately_status == 1 or instance.book.create_datetime ==  request.user.id ):
            serializer = self.get_serializer(instance)
            return DetailResponse(data=serializer.data, msg="获取成功")
        else:
            return DetailResponse(data=[], msg="获取成功")

